import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Table,
  Upload,
  message,
  Space,
  Popconfirm,
} from "antd";
import React, { useEffect, useState } from "react";
import {
  CheckOutlined,
  DeleteOutlined,
  EditOutlined,
  FormOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import {
  reqTrademarkList,
  reqAddTrademark,
  reqDeleteTrademark,
  reqUpdateTrademark,
} from "@/api/trademark.ts/trademark";
import { trademarkItemType } from "@/api/trademark.ts/trademark";
import { ColumnsType } from "antd/lib/table";
import { UploadChangeParam } from "antd/lib/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import { useForm } from "antd/lib/form/Form";
import type { trademarkListType } from "@/api/trademark.ts/trademark";

export default function Trademark() {
  // 图片
  const [file, setFile] = useState(false);

  const [title, setTitle] = useState("");

  // 1.品牌列表
  const [trademarkList, SetTrademarkList] = useState<trademarkListType>([]);
  const [id, setId] = useState(NaN);
  // 2.当前页
  const [current, setCurrent] = useState(1);
  // 3.每页条数
  const [pageSize, setPageSize] = useState(5);
  // 4.总条数
  const [total, setTotal] = useState(0);
  // 5.是否打开添加框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 6.品牌名称
  const [tmName, setTmName] = useState("");
  // 7.图片的url
  const [logoUrl, setLogoUrl] = useState("");
  // 8.表单数据对象
  const [form] = useForm();
  // 9.BASE_URL
  const BASE_URL = "http://gmall-h5-api.atguigu.cn";
  //   加载
  const [loading, setLoading] = useState(false);

  // 10.table的列
  const columns: ColumnsType<trademarkItemType> = [
    {
      title: "序号",
      render(text, record, index) {
        return index + 1;
      },
      align: "center",
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
      //   key: 'tmName',
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      //   key: 'logoUrl',
      render(val) {
        return <img src={val} alt="LOGO" width={100} />;
      },
    },

    {
      title: "操作",
      key: "action",
      render: (value, row, index) => (
        <>
          <Button
            type="primary"
            onClick={() => {
              showModal(row);
            }}
          >
            <FormOutlined />
          </Button>
          <Popconfirm
            title={`确定删除${row.tmName}吗?`}
            onConfirm={deleteOne(row.id as number)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              className="ml"
            />
          </Popconfirm>
        </>
      ),
    },
  ];

  useEffect(() => {
    getTrademarkList();
  }, []);

  //   请求品牌分页列表
  const getTrademarkList = async (
    page: number = current,
    limit: number = pageSize
  ) => {
    const result = await reqTrademarkList(page, limit);
    // console.log(result);

    setCurrent(result.current);
    setPageSize(result.size);
    setTotal(result.total);
    SetTrademarkList(result.records);

    message.success("获取品牌分页列表成功");
  };

  // 弹窗相关
  //   新增品牌的打开弹窗
  const showModal = (row?: trademarkItemType) => {
    setIsModalOpen(true);

    setId(-1);
    if (row?.id) {
      setTitle("修改品牌");

      // 有id是修改 回填数据
      form.setFieldsValue({
        tmName: row.tmName,
      });
      setLogoUrl(row.logoUrl);
      setId(row.id);
    } else {
      //    没有id是新增 清空数据
      setTitle("新增品牌");

      form.setFieldsValue({
        tmName: "",
      });
      setLogoUrl("");
    }
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //   表单相关
  //   请求新增品牌
  const onFinish = async (values: trademarkItemType) => {
    console.log("Success:", values);
    setTmName(values.tmName);

    if (id === -1) {
      await form.validateFields();
      await reqAddTrademark(values.tmName, logoUrl);
      message.success("新增品牌成功");
    } else {
      const tmInfo = {
        id,
        tmName: values.tmName,
        logoUrl,
      };
      await reqUpdateTrademark(tmInfo);

      message.success("修改品牌成功");
    }

    getTrademarkList();

    setIsModalOpen(false);
  };

  //   上传图片相关
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      console.log(info.file.response.data, "77");
      setLoading(false);
      setLogoUrl(info.file.response.data);
    }
  };

  const normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  //   删除品牌
  const deleteOne = (id: number) => {
    return async () => {
      await reqDeleteTrademark(id);
      message.success("删除品牌成功");
      getTrademarkList();
    };
  };

  //   回填数据
  //   const updateTrademark = (row: trademarkItemType) => {
  //     return () => {
  //       setIsModalOpen(true);
  //       console.log(row.logoUrl);

  //       const { tmName, logoUrl } = row;

  //       form.setFieldsValue({
  //         tmName: tmName,
  //         // logoUrl: logoUrl,
  //         // fileList: [logoUrl],
  //       });
  //     };
  //   };

  //
  //   const onRemove = (file) => {
  //     setFile(true);

  //   };

  return (
    <Card>
      <Button type="primary" onClick={() => showModal()}>
        <PlusOutlined />
        添加
      </Button>
      <Table
        bordered
        columns={columns}
        rowKey="id"
        dataSource={trademarkList}
        pagination={{
          current,
          pageSize,
          total,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: getTrademarkList,
        }}
      />

      <Modal
        title={title}
        visible={isModalOpen}
        onCancel={handleCancel}
        footer={[]}
      >
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[{ required: true, message: "请输入品牌名称" }]}
          >
            <Input placeholder="输入品牌名称" />
          </Form.Item>

          <Form.Item
            label="品牌Logo"
            name="logoUrl"
            valuePropName="fileList"
            rules={[{ required: true, message: "请上传图片" }]}
            getValueFromEvent={normFile}
          >
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={`${BASE_URL}/admin/product/fileUpload`}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {logoUrl ? (
                <img src={logoUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item style={{ float: "right", marginTop: -30 }}>
            <Button type="primary" htmlType="submit" icon={<CheckOutlined />}>
              确定
            </Button>
            <Button className="ml" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
